<?php
/**
 * Created by PhpStorm.
 * User: dy
 * Date: 2019/12/19
 * Time: 16:32
 */
namespace app\admin\controller;
use app\admin\model\Admin;
use app\admin\model\AdminActionLogModel;
use app\admin\validate\LoginValidate;
use app\common\controller\BackendController;
use util\CommonUtil;

class Login extends BackendController
{
    protected $noNeedLogin = [
        'login',
    ];
    /**
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(){
        if($this->auth->isLogin()){
            $redirect = $this->request->get('redirect');
            if(!$redirect){
                $redirect = url("admin/index/index");
            }
            $this->redirect($redirect);
        }
        if($this->request->isPost()){
            $param = $this->request->post();
            if(!LoginValidate::instance()->scene('admin')->check($param)){
                $this->error(LoginValidate::instance()->getError());
            }
            $admin_info = Admin::where('username|phone|email',$param['username'])->find();
            if(empty($admin_info)){
                $this->error("此管理员不存在！");
            }
            if(!password_verify($param['password'],$admin_info['password'])){
                $this->error("密码错误");
            }
            $admin_info['last_login_time'] = $admin_info->getData('login_time');
            $admin_info['last_login_ip'] = $admin_info['login_ip'];
            $admin_info['login_ip'] = $this->request->ip();
            $admin_info['login_time'] = time();
            $admin_info['login_count'] = $admin_info['login_count']+1;
            $admin_info->save();
            $auth = ['id' => $admin_info['id'], 'login_time' => time()];

            session('admin_info', $admin_info);
            session('admin_auth', $auth);
            session('admin_auth_sign', CommonUtil::instance()->data_auth_sign($auth));
            if($redirect = $this->request->get('redirect')){
                if(strpos($redirect,'http') === false){
                    $url = url($redirect);
                }else {
                    $url = $redirect;
                }
            }else{
                $url = url('index/index');
            }
            AdminActionLogModel::logAdd('系统登录','管理员:'.$param['username']);
            $this->success('登录成功',$url);
        }
        return view();
    }

    public function logout(){
        AdminActionLogModel::logAdd('退出系统','管理员:'.$this->auth->username);
        clearLoginSession();
        $this->success('退出成功！');
    }
}